//
//  VC3.m
//  PCAForWar
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "VC3.h"
#import "WaterFlowLayout.h"
#import "CellForWater.h"
#import "Model.h"
#import "UIImageView+WebCache.h"
#import <MJRefresh.h>
#import "NetWorkHandler.h"
#import "NetworkingHandle.h"
#import "VC3ForImage.h"
#import <DKNightVersion.h>
#import "NetWorkingHandler.h"

@interface VC3 () <UICollectionViewDataSource,UICollectionViewDelegate,WaterFlowDelegate>

@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, retain) NSMutableArray *arrForImage;
@property (nonatomic, retain) NSString *strForShangLa;
@property (nonatomic, assign) NSInteger pageForShangLa;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, retain) NSMutableArray *arrForDate;


@end

@implementation VC3

- (void)dealloc{
    
    _collectionView.dataSource = nil;
    _collectionView.delegate = nil;
    
    [_collectionView release];
    [_dataArr release];
    [_arrForImage release];
    [_strForShangLa release];
    [_arrForDate release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.dataArr = [NSMutableArray array];
    
    self.arrForDate = [NSMutableArray array];
    
    self.strForShangLa = @"page=1&processID=getPicList&pageSize=24&";
    
    // 设置默认的页数为第一页
    self.pageForShangLa = 1;
    
    [self handleData];
    [self createNavigation];
    
    
    WaterFlowLayout *flowLayout = [[WaterFlowLayout alloc] init];
    
    flowLayout.delegate = self;
    
    CGFloat w = ([UIScreen mainScreen].bounds.size.width - 30) / 2;
    flowLayout.itemSize = CGSizeMake(w, 0);
    flowLayout.insertItemSpacing = 10;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.collectionView.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[CellForWater class] forCellWithReuseIdentifier:@"CELL"];
    
    [self header];
    [self shangLa];
    
    [flowLayout release];
    [_collectionView release];
}

#pragma mark 夜间模式
- (void)viewDidAppear:(BOOL)animated {
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    
}

#pragma mark 解析数据
- (void)handleData {
    
    [NetWorkingHandler handleDataByStr:@"http://admin.militaryapp.china.com/News/NewsServlet.do" body:self.strForShangLa header:@"application/x-www-form-urlencoded; charset=UTF-8"  block:^(id result) {
        
        NSArray *arrDown = [result objectForKey:@"data"];
        
        // 遍历数组, 生成model对象.
        for (NSDictionary *dic in arrDown) {
            
            Model *model = [[Model alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            NSRange range = {66,10};
            
            NSString *str = [model.PicUrl substringWithRange:range];
            
            [self.arrForDate addObject:str];
            
            [self.dataArr addObject:model];
            
            [model release];
        }
        
        if (!self.arrForImage) {
            
            self.arrForImage = [NSMutableArray array];
        }
        
        // 创建一个新数组, 里面初始化放置占位图image, 个数和model所在数组一样.
        for (NSInteger i = self.count; i < self.dataArr.count; i++) {
            
            [self.arrForImage addObject:[UIImage imageNamed:@"jiazai"]];
        }
        
        self.count = self.dataArr.count;
        
        for (Model *model2 in self.dataArr) {
            
            // 遍历数组, 记录model所在index
            NSInteger index = [self.dataArr indexOfObject:model2];
            
            // 异步加载图片, 同时传入model的index, 当图片下载完之后, 在arrImage数组中, 根据index替换原图片(占位图).
            [NetworkingHandle networkingWithURL:model2.PicUrl withIndex:index completeHandel:^(NSURLResponse *response, NSData *data, NSInteger index) {
                
                UIImage *image = [UIImage imageWithData:data];
                
                [self.arrForImage replaceObjectAtIndex:index withObject:image];
                
                [self.collectionView reloadData];
                
            }];
            
        }
        
        [self.collectionView reloadData];
        
        [self.collectionView.mj_footer endRefreshing];
        
        
        
    }];
    
}

#pragma mark  创建NavigationController
- (void)createNavigation {
    
    self.navigationItem.title = @"图库";
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName : [UIFont fontWithName:@"AmericanTypewriter-Bold" size:22],
                                                                       }];
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorWithColors([UIColor redColor], [UIColor colorWithRed:39 / 256.f green:39 / 256.f blue:39 / 256.f alpha:1]);
    
    
    
}

#pragma mark 协议方法
- (CGFloat)heightForItemIndexPath:(NSIndexPath *)indexPath {
    
    return [CellForWater height:self.arrForImage[indexPath.item]] + 50;
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.arrForImage.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CellForWater *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    
    cell.imageView.image = [self.arrForImage objectAtIndex:indexPath.item];
    
    cell.labelForTitle.text = [[self.dataArr objectAtIndex:indexPath.item] Title];
    
    return cell;
}

#pragma mark 瀑布流点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    VC3ForImage *vc3 = [[VC3ForImage alloc] init];
    
    self.hidesBottomBarWhenPushed = YES;
    
    Model *model = model = self.dataArr[indexPath.item];
    
    vc3.ID = [model.NewsId integerValue];
    
    vc3.date = self.arrForDate[indexPath.item];
    
    [self.navigationController pushViewController:vc3 animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
    
    [vc3 release];
}

#pragma mark 下拉刷新
- (void)header {
    
    self.strForShangLa = @"page=1&processID=getPicList&pageSize=24&";
    
    self.pageForShangLa = 1;
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewAction)];
    
    [self.collectionView.mj_header beginRefreshing];
    
}

- (void)loadNewAction {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.collectionView.mj_header endRefreshing];
        
        [self.collectionView reloadData];
        
    });
}

#pragma mark 上拉刷新
- (void)shangLa {
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        self.strForShangLa = [NSString stringWithFormat:@"page=%ld&processID=getPicList&pageSize=24&", ++self.pageForShangLa];
        
        [self handleData];
        
    }];
    
    self.collectionView.mj_footer = footer;
}















- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
